package com.mtw.bbs.common.core.security.context.strategy;

import com.mtw.bbs.common.core.security.context.SecurityContext;
import com.mtw.bbs.common.core.security.context.SecurityContextHolderStrategy;
import com.mtw.bbs.common.core.security.context.SecurityContextImpl;
import org.springframework.util.Assert;

/**
 * 基于InheritableThreadLocal的上下文策略
 */
public class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {


    private static final ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal<>();


    /**
     * 清理
     */
    public void clearContext() {
        contextHolder.remove();
    }

    /**
     * 获取
     */
    public SecurityContext getContext() {
        SecurityContext ctx = contextHolder.get();

        if (ctx == null) {
            ctx = createEmptyContext();
            contextHolder.set(ctx);
        }

        return ctx;
    }


    /**
     * 设置
     */
    public void setContext(SecurityContext context) {
        Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
        contextHolder.set(context);
    }

    /**
     * 创建一个空的上下文
     */
    public SecurityContext createEmptyContext() {
        return new SecurityContextImpl();
    }
}
